package com.biluo.mvs.di

import android.util.Log
import com.biluo.mvs.utils.GlobalData
import com.biluo.mvs.utils.Utils
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@InstallIn(SingletonComponent::class)
@Module
class NetworkClientModule {

    @Provides
    @Singleton
    fun OkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor { chain ->
                // 请求处理
                var request = chain.request()
                request = request.newBuilder().header("token", GlobalData.token).build()
                // 响应处理
                val response = chain.proceed(request)
                Log.d(GlobalData.LOG_TAG, "请求：${request.url}, token: ${GlobalData.token}")
                if (response.code == 401) {
                    Log.d(GlobalData.LOG_TAG, "token失效")
                    Utils.showToast("token失效，请重新登录")
                }
                response
            }
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)    // 是否重试
            .build()
    }
}